package top.kikt.book.core.handlers

import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.core.handlers.common.CommonHandler
import top.kikt.book.core.handlers.common.CommonMenuHandler
import java.nio.charset.Charset

class PinShu : BaseBookHandler(), CommonHandler {
    override fun forceCharset(): Charset? = null

    override val host: String
        get() = "www.pinshu.org"

    override fun createNodeFilter(document: Document, nodes: Elements): CommonMenuHandler.NodeFilter {
        return NodeFilter(document)
    }

    private class NodeFilter(document: Document) : CommonMenuHandler.NodeFilter {

        var firstChapter: Element? = null

        init {
            val dl = document.select("#list > dl")
            val childNodes = dl[0].childNodes().toList()
                .filterIsInstance<Element>()

            for ((index, childNode) in childNodes.withIndex()) {
                val tagName = childNode.tagName()
                if (tagName == "dt" && childNode.text().contains("正文")) {
                    firstChapter = childNodes[index + 1].select("dd > a")[0]
                    break
                }
            }

            if (firstChapter == null) {
                throw Exception("Can't find first chapter")
            }

            println("firstChapter: $firstChapter")
        }

        private var find = false

        override fun filter(index: Int, element: Element): Boolean {
            if (element == firstChapter) {
                find = true
            }

            return find
        }
    }

    override fun watermark(): Map<Regex, String> {
        return mapOf(
            Regex("品书网 www\\.pinshu\\.org.+！") to "　　 \n"
        )
    }
}